const pool = require('../config/db'); // 假设已正确配置 MySQL 连接池

// 获取所有商品
exports.getAllProducts = async (req, res) => {
  try {
    const [results] = await pool.execute('SELECT * FROM product');
    
    const processedProducts = results.map(item => {
      item.url = `/img/${item.url}`; // 拼接为 /img/27.jpg 格式
      return item;
    });
    res.json(processedProducts);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
// 新增按 name 和 type 搜索的方法
exports.getFilteredProducts = async (req, res) => {
  try {
      const { search = '' } = req.query;
      const sql = `
          SELECT * FROM product 
          WHERE name LIKE ? OR type LIKE ? 
          ORDER BY id DESC
      `;
      const [results] = await pool.execute(sql, [`%${search}%`, `%${search}%`]);

      const processedProducts = results.map(item => {
        item.url = `/img/${item.url}`; // 拼接为 /img/27.jpg 格式
        return item;
      });
      res.json(processedProducts);
  } catch (error) {
      res.status(500).json({ message: '搜索商品失败', error: error.message });
  }
};


// 获取单个商品
exports.getProductById = async (req, res) => {
  try {
    const [results] = await pool.execute('SELECT * FROM product WHERE id =?', [req.params.id]);
    if (results.length === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    results[0].url = `/img/${results[0].url}`;
    res.json(results[0]);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 创建商品
exports.createProduct = async (req, res) => {
  const { name, type, description, is_available, price, village_collective_id, inventory, url } = req.body;
  try {
    const [result] = await pool.execute(
      'INSERT INTO product (name, type, description, is_available, price, village_collective_id, inventory, url) VALUES (?,?,?,?,?,?,?,?)',
      [name, type, description, is_available, price, village_collective_id, inventory, url]
    );
    res.status(201).json({ id: result.insertId, ...req.body });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

// 更新商品
exports.updateProduct = async (req, res) => {
  const { name, type, description, is_available, price, village_collective_id, inventory, url } = req.body;
  try {
    const [result] = await pool.execute(
      'UPDATE product SET name =?, type =?, description =?, is_available =?, price =?, village_collective_id =?, inventory =?, url =? WHERE id =?',
      [name, type, description, is_available, price, village_collective_id, inventory, url, req.params.id]
    );
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    res.json({ id: req.params.id, ...req.body });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

// 删除商品
exports.deleteProduct = async (req, res) => {
  try {
    const [result] = await pool.execute('DELETE FROM product WHERE id =?', [req.params.id]);
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    res.json({ message: '商品删除成功' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};